package service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import dao.BaseDAO;

import entity.Dir;
import entity.Note;
import service.NoteService;
@Service("noteService")
public class NoteServiceImpl implements NoteService {

	//依赖注入DAO
	@Resource(name="baseDAO")
	private BaseDAO baseDAO;
	public BaseDAO getBaseDAO() {
		return baseDAO;
	}
	public void setBaseDAO(BaseDAO baseDAO) {
		this.baseDAO = baseDAO;
	}
	@Override
	public List<Dir> listDirsByUser(int userId) {
		String hql = "select u.dirs from User u where u.id="+userId;
		return (List<Dir>)baseDAO.query(hql);
	}
	//列出用户笔记
	@Override
	public List<Note> listNoteByUser(int userId, int pageNo, int pageSize) {
		String hql = "select new Note(n.id,n.title,n.createTime,n.summary,n.label) from Note n where n.user.id = '"+userId+"' order by n.id desc";		
		return (List<Note>) baseDAO.query(hql, pageNo, pageSize);
	}
	//统计用户的日志总数
	@Override
	public int countNumByUser(int userId) {
		String hql = "select count(*) from Note n where n.user.id='"+userId+"'";
		return baseDAO.countQuery(hql);
	}
	@Override
	public List<Note> listNoteByDir(int dirId, int pageNo, int pageSize) {
		String hql = "from Note n where n.dir.id='"+dirId+"' order by n.id desc";
		return baseDAO.query(hql, pageNo, pageSize);
	}
	
	
	@Override
	public Note findNoteById(int noteId,int userId) {
		String hql = "from Note n where n.id= '"+noteId+"' and n.user.id='"+userId+"'";
		return (Note)baseDAO.loadObject(hql);
	}
	
	@Override
	public int countNumByDir(int dirId) {
		Dir d = (Dir)baseDAO.loadById(Dir.class, dirId);
		return d.getnCount();
	}

	@Override
	public int saveNote(Note note) {
		return baseDAO.saveEntity(note);
	}

	@Override
	public int updateNote(Note note) {
		baseDAO.saveOrUpdate(note);
		return 0;
	}
	@Override
	public int deleteNote(int noteId,int userId) {
		String hql = "delete Note n where n.id ='"+noteId+"' and n.user.id='"+userId+"'";
		return baseDAO.update(hql);
	}
	@Override
	public void dirPlus(int dirId) {
		String hql = "update Dir d  set d.nCount = d.nCount +1 where d.id = '"+dirId+"'";
		baseDAO.update(hql);
	}
	@Override
	public void dirMinus(int dirId) {
		String hql ="update Dir d set d.nCount = d.nCount -1 where d.id='"+dirId+"'";
		baseDAO.update(hql);
	}
	@Override
	public Dir findDirByNote(int noteId) {
		String hql = "select n.dir from Note n where n.id='"+noteId+"'";
		return (Dir)baseDAO.loadObject(hql);
	}

	@Override
	public int delDir(int dirId) {
		baseDAO.delById(Dir.class, dirId);
		return 1;
	}
	@Override
	public int rnDir(int dirId, String dirName) {
		String hql = "update Dir d set d.dirName = '"+dirName+"'where d.id = '"+dirId+"'";
		baseDAO.update(hql);
		return 1;
	}
	@Override
	public int svDir(Dir dir) {
		return baseDAO.saveEntity(dir);
	}
	
	

}
